package world

import (
	"fmt"
	"time"

	"public.com/goutil/logUtil"
)

var (
	serverModuleName = "world"
)

// 启动游戏世界
func StartGameWorld() {
	totalErrList := make([]error, 0, 16)

	// 从数据库中加载所有的配置数据
	start := time.Now().Unix()
	loadErrList := LoadMgr.CallAll()
	if len(loadErrList) > 0 {
		totalErrList = append(totalErrList, loadErrList...)
	}
	end := time.Now().Unix()
	logUtil.InfoLog("LoadMgr costs %d seconds.", end-start)

	// 验证所有的数据是否合法
	start = time.Now().Unix()
	verifyErrList := VerifyMgr.CallAll()
	if len(verifyErrList) > 0 {
		totalErrList = append(totalErrList, verifyErrList...)
	}
	end = time.Now().Unix()
	logUtil.InfoLog("VerifyMgr costs %d seconds.", end-start)

	//　将所有的配置数据进行转换（如果需要）
	start = time.Now().Unix()
	convertErrList := ConvertMgr.CallAll()
	if len(convertErrList) > 0 {
		totalErrList = append(totalErrList, convertErrList...)
	}
	end = time.Now().Unix()
	logUtil.InfoLog("ConvertMgr costs %d seconds.", end-start)

	// 将验证后的数据应用到正式数据中
	start = time.Now().Unix()
	applyErrList := ApplyMgr.CallAll()
	if len(applyErrList) > 0 {
		totalErrList = append(totalErrList, applyErrList...)
	}
	end = time.Now().Unix()
	logUtil.InfoLog("ApplyMgr costs %d seconds.", end-start)

	// 打印数据
	// start = time.Now().Unix()
	// printErrList := PrintMgr.CallAll()
	// if len(printErrList) > 0 {
	// 	totalErrList = append(totalErrList, printErrList...)
	// }
	// end = time.Now().Unix()
	// logUtil.InfoLog("PrintMgr costs %d seconds.", end-start)

	// 清理数据(临时变量)
	start = time.Now().Unix()
	cleanErrList := CleanMgr.CallAll()
	if len(cleanErrList) > 0 {
		totalErrList = append(totalErrList, cleanErrList...)
	}
	end = time.Now().Unix()
	logUtil.InfoLog("CleanMgr costs %d seconds.", end-start)

	// 设置环境
	start = time.Now().Unix()
	setupErrList := SetupMgr.CallAll()
	if len(setupErrList) > 0 {
		totalErrList = append(totalErrList, setupErrList...)
	}
	end = time.Now().Unix()
	logUtil.InfoLog("SetupMgr costs %d seconds.", end-start)

	// 初始化完成
	start = time.Now().Unix()
	completeErrList := CompleteMgr.CallAll()
	if len(completeErrList) > 0 {
		totalErrList = append(totalErrList, completeErrList...)
	}
	end = time.Now().Unix()
	logUtil.InfoLog("CompleteMgr costs %d seconds.", end-start)

	// 检查全部的错误信息
	if len(totalErrList) > 0 {
		fmt.Println("-------------------------------------------------------------------------------------")
		fmt.Printf("There are %d error(s):\n", len(totalErrList))
		for i, v := range totalErrList {
			fmt.Printf("No.%d: %v\n", i+1, v)
		}
		panic("Please fix them first.")
	}

	// 启动定时器
	go startTimer()
}
